<template>
  <div class="myUser">
    <div class="wrap">
      <div style="margin-top: 60px" class="Breadcrumb">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>个人中心</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="tabs">
        <el-tabs :tab-position="tabPosition" class="demo-tabs">
          <el-tab-pane label="个人信息">
            <div class="teacherAdd">
              <el-form
                ref="ruleFormRef"
                style="max-width: 600px"
                :model="ruleForm"
                :rules="rules"
                label-width="auto"
                class="demo-ruleForm"
                :size="formSize"
                status-icon
              >
                <el-form-item label="用户头像" prop="avatar">
                  <el-upload
                    class="avatar-uploader"
                    :action="uploadUrl + '/oss/upload-img'"
                    :data="{ cateDir: 'teacher' }"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                  >
                    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon"
                      ><Plus
                    /></el-icon>
                  </el-upload>
                </el-form-item>
                <el-form-item label="用户名" prop="username">
                  <el-input v-model="ruleForm.username" />
                </el-form-item>

                <el-form-item label="昵称" prop="nickname">
                  <el-input v-model="ruleForm.nickname" />
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                  <el-input v-model="ruleForm.phone" />
                </el-form-item>

                <el-form-item label="性别" prop="sex">
                  <el-select
                    v-model="ruleForm.sex"
                    clearable
                    placeholder="请选择性别"
                  >
                    <el-option value="1" label="男" />
                    <el-option value="2" label="女" />
                  </el-select>
                </el-form-item>
                <el-form-item label="用户签名" prop="sign">
                  <el-input type="textarea" v-model="ruleForm.sign" rows="8" />
                </el-form-item>

                <el-form-item>
                  <el-button type="primary" @click="submitForm(ruleFormRef)">
                    保存
                  </el-button>
                  <el-button @click="resetForm(ruleFormRef)">重置</el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-tab-pane>
          <el-tab-pane label="历史记录">
            <div class="watchHistoryList">
              <div
                class="courseBox"
                @click="towatchHistoryVideo(item.vid, item.lastPosition,item.videoId,item.courseId)"
                v-for="item in watchHistoryList"
                :key="item.id"
                style="margin-bottom: 20px"
              >
                <div class="left">
                  <img :src="item.cover" />
                </div>
                <div class="right">
                  <div class="title">
                    <h3>{{ item.courseTitle }}</h3>
                  </div>
                  <div class="watchTime">
                    <h3 style="margin-top: 20px;">{{ item.watchTime }}</h3>
                  </div>
                  <div class="lastPosition">
                    <h3  style="margin-top: 30px;">
                      {{ item.videoTitle }} 看到 00:0{{ item.lastPosition }}
                    </h3>
                  </div>
                </div>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="订单列表" style="margin-top: 20px;" >
           
            <div class="table"  >
                <el-table :data="tableData">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="id" label="序号" width="50" />
            <el-table-column prop="orderNo" label="订单号" width="150" />
            <el-table-column prop="courseTitle" label="课程名称" width="100" />
            <el-table-column label="课程封面" width="150">
              <template #default="scope">
                <div class="courseCover">
                  <img
                    :src="scope.row.courseCover"
                    alt=""
                    style="width: 130px; height: 100px"
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="teacherName" label="讲师名称" width="100" />
            <el-table-column prop="nickname" label="用户名称" width="100" />
            <el-table-column prop="phone" label="手机号" width="100" />
            <el-table-column prop="totalFee" label="金额" width="100" />
            <el-table-column prop="status" label="订单状态" width="100">
              <template #default="scope">
                <el-tag v-if="scope.row.status === 0" type="success"
                  >未支付</el-tag
                >
                <el-tag v-if="scope.row.status === 1">已支付</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button type="danger" link @click="del(scope.row.id)"
              ><el-icon>
                <Delete /> </el-icon
              >删除</el-button
            >
          </template>
        </el-table-column>
          </el-table>
            </div>
          
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { Action, ElMessage, ElMessageBox, TabsInstance } from "element-plus";
import { reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import type {
  ComponentSize,
  FormInstance,
  FormRules,
  UploadProps,
} from "element-plus";
import axios from "../../assets/js/axios";
const router = useRouter();
// 获取路由对象
const route = useRoute();
const watchHistoryList = ref<any>([]);
// 从查询参数中获取 userId
const userId = route.query.userId;
console.log("User ID:", userId);
const tableData = ref<any[]>([]);
const tabPosition = ref<TabsInstance["tabPosition"]>("left");

//接收传递过来的id
if (userId) {
  //修改元信息标题
  console.log("User ID:", userId);
  // 发送请求显示编辑的信息
  axios.get("/serviceedu/edu-user/getById/" + userId, {}).then((res: any) => {
    console.log(res);
    ruleForm.id = res.data.data.id;
    ruleForm.username = res.data.data.username;
    ruleForm.nickname = res.data.data.nickname;
    ruleForm.phone = res.data.data.phone;
    ruleForm.sex = res.data.data.sex;
    ruleForm.sign = res.data.data.sign;
    imageUrl.value = res.data.data.avatar;
  });
}

interface RuleForm {
  id?: number;
  username: string;
  nickname: string;
  phone: string;
  sex: number;
  sign: string;
  avatar: string;
}

const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  username: "",
  nickname: "",
  phone: "",
  sex: 0,
  sign: "",
  avatar: "",
});
const imageUrl = ref("");
const uploadUrl = "http://localhost:9001/";
// 文件上传成功的方法
const handleAvatarSuccess: UploadProps["onSuccess"] = (response) => {
  console.log("response:", response);
  imageUrl.value = response.data.url;
  ruleForm.avatar = response.data.url;
};

//点击保存
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!", ruleForm);

      if (route.query.id) {
        // 进行保存修改
        axios
          .put("/serviceedu/edu-user/updaterUser", ruleForm)
          .then((res: any) => {
            if (res.code === 200) {
              ElMessage({
                type: "success",
                message: "修改用户成功",
              });
              // 跳转列表页
              router.push("/myUser");
            }
          });
      }
    }
  });
};

//点击重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

//获取课程历史记录列表
if (userId) {
  axios
    .get("/serviceedu/edu-watchhistory/watchhistory/" + userId, {})
    .then((res: any) => {
      if ((res.code = 200)) {
        watchHistoryList.value = res.data.data;
      }
    });
}
const towatchHistoryVideo = (vid: any, lastPosition: any, videoId: any, courseId: any) => {
  console.log("Navigating with:", { vid, lastPosition, videoId, courseId });
  router.push({
    path: "/video",
    query: { vid, lastPosition: Math.floor(lastPosition), videoId, courseId },
  });
};
//查询订单
const getUserOrder=()=>{
   axios
    .get("/serviceedu/edu-order/getUserOrder" + userId, {})
    .then((res: any) => {
      if ((res.code = 200)) {
tableData.value = res.data.data;
      }
    });
}
getUserOrder()
const del = (id: number) => {
    ElMessageBox.alert("确认删除吗？", "提示", {
      // if you want to disable its autofocus
      // autofocus: false,
      confirmButtonText: "确认",
      callback: (action: Action) => {
        console.log(action);
        if (action === "confirm") {
          axios.del("/serviceedu/edu-order/delOrder/" + id,{} ).then((res: any) => {
            if (res.code === 200) {
              //提示删除成功
              ElMessage({
                message: "删除数据成功",
                type: "success",
              });
              // 刷新列表
              getUserOrder()
            }
          });
        }
      },
    });
  };
</script>

<style lang="less" scoped>
.myUser {
  background-color: #f7f7f7;
  padding: 20px;
  .tabs {
    margin-top: 30px;
    background-color: #ffffff;
    border-radius: 12px;
    box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
    transition: box-shadow 0.3s ease;
    .demo-tabs {
      .el-tabs__content {
        margin-left: 400px;
        .teacherAdd {
          margin-left: 200px;
          :deep .avatar-uploader {
            .avatar {
              width: 178px;
              height: 178px;
              display: block;
            }
            .el-upload {
              border: 1px dashed #cccccc;
              border-radius: 6px;
              cursor: pointer;
              position: relative;
              overflow: hidden;
              transition: var(--el-transition-duration-fast);
            }
            .el-upload:hover {
              border-color: #409eff;
            }
          }
          .el-icon.avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            text-align: center;
          }
        }
        .watchHistoryList {
          .courseBox {
            padding: 20px;
            width: 1075px;
            height: 180px;
            border: #b1b3b8 1px solid;
            margin: 20px;
            display: flex;
            .left {
              img{
               width: 300px; height: 150px
              }
            }
            .right {
              h3{
                margin-left: 20px;
              }
            }
          }
        }
      }
    }
  }
}
</style>
